#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time    : 2021/3/5 16:08
# @Author  : zhaohexin
# @Email   : 1483643520@xxx.com
# @File    : crud.py
# @Software: PyCharm
# @FileDescription：角色具体逻辑表

from sqlalchemy.orm import Session

from apps.system.roles import model
from apps.system.users import model as userModel


def get_role(db: Session, role_id: int):
    """
    获取单条角色数据
    :param db:
    :param role_id:
    :return:
    """
    return db.query(model.Roles).filter(model.Roles.id == role_id).first()


def get_roles(db: Session, page: int, size: int, sort: str = "id"):
    """
    获取全部角色数据
    :param sort:
    :param db:
    :param page:
    :param size:
    :return:
    """
    # 计算偏移量
    offset = page * size
    return db.query(model.Roles).order_by(sort).offset(offset).limit(size).all()


def get_roles_by_user(db: Session, user_id: int):
    """
    根据所属用户进行角色查询
    :param db:
    :param user_id:
    :return:
    """
    roles = [role.role_id for role in db.query(userModel.UsersRoles).filter(userModel.UsersRoles.user_id == user_id)]
    return db.query(model.Roles).filter(model.Roles.id.in_(roles)).all()
